package com.quan.system.web.controller;

import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quan.common.bean.PageBean;
import com.quan.common.bean.R;
import com.quan.common.core.MyBaseController;
import com.quan.system.common.vo.RolePermissionVo;
import com.quan.system.entity.SystemRole;
import com.quan.system.entity.SystemRolePermission;
import com.quan.system.service.SystemRolePermissionService;
import com.quan.system.service.SystemRoleService;

/**
 * <p>
 * 通用用户权限系统-角色表 前端控制器
 * </p>
 *
 * @author 杨浩泉
 * @since 2019-06-05
 */
@RestController
@RequestMapping("/system/role")
public class SystemRoleController extends MyBaseController {
	
	@Autowired 
	private SystemRoleService service;
	
	@Autowired 
    private SystemRolePermissionService rolePermissionService;

    /**
	 * 添加
	 * 
	 * @param entity
	 * @param bindingResult
	 * @return
	 */
	@PostMapping("/add")
	public Object add(@Valid @RequestBody SystemRole entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return R.warning(bindingResult.getFieldError().getRejectedValue().toString());
		}
		if(this.service.hasExist("code", entity.getCode(), SystemRole.class)) {
			return R.warning("该值已存在");
		}
		boolean save = this.service.save(entity);
		if (save) {
			return R.ok("提交成功");
		} else {
			return R.failure("提交失败");
		}
	}

	/**
	 * 根据ID删除
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/deleteById/{id}")
	public Object deleteById(@PathVariable String id) {
		if (StringUtils.isNotBlank(id)) {
			boolean remove = this.service.removeById(id);
			if (remove) {
				return R.ok();
			} else {
				return R.failure("通过ID删除失败：[ " + id + " ]");
			}
		}
		return R.failure("请选项需要删除的记录");
	}

	/**
	 * 批量删除
	 * 
	 * @param params idList:["1","2"]
	 * @return
	 */
	@PostMapping("/deleteBatchIds")
	public Object deleteBatchIds(@RequestBody Map<String, Object> params) {
		if (null != params && !params.isEmpty()) {
			List<Long> idList = JSON.parseArray(params.get("idList").toString(), Long.class);
			boolean remove = this.service.removeByIds(idList);
			if (remove) {
				return R.ok();
			} else {
				return R.failure("通过ID删除失败：[ " + idList + " ]");
			}
		}
		return R.failure("请选项需要删除的记录");
	}

	/**
	 * 修改
	 * 
	 * @param entity
	 * @param bindingResult
	 * @return
	 */
	@PostMapping("/update")
	public Object update(@Valid @RequestBody SystemRole entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return R.failure(bindingResult.getFieldError().getDefaultMessage().toString());
		}
		boolean update = this.service.updateById(entity);
		if (update) {
			return R.ok("修改成功");
		} else {
			return R.failure("修改失败");
		}
	}

	/**
	 * 根据ID查询
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/get/{id}")
	public Object get(@PathVariable Long id) {
		SystemRole entity = this.service.getById(id);
		if (null != entity) {
			return R.ok(entity);
		} else {
			return R.failure("通过ID查询失败：[ " + id + " ]");
		}
	}

	/**
	 * 查询所有数据，不分页
	 * 
	 * @param entity
	 * @return
	 */
	@GetMapping(value = "/list")
	public Object list(SystemRole entity) {
		return R.ok(this.service.list(new QueryWrapper<SystemRole>(entity)));
	}

	/**
	 * 分页查询数据
	 * 
	 * @param entity
	 * @return
	 */
	@GetMapping(value = "/page")
	public Object page(SystemRole entity) {
		return R.ok(this.service.selectPage(new QueryWrapper<SystemRole>(entity).orderByDesc("ctime"), new PageBean(request)));
	}
	
	/**
	 * 根据角色ID获取对应的权限
	 * @param entity
	 * @return
	 */
	@GetMapping(value = "/getPermissionByRoleId/{roleId}")
	public Object getPermissionByRoleId(@PathVariable String roleId) {
		QueryWrapper<SystemRolePermission> queryWrapper = new QueryWrapper<SystemRolePermission>();
		queryWrapper.eq("role_id", roleId).select("permission_id", "menu_id");
		return R.ok(this.rolePermissionService.list(queryWrapper));
	}
	
	
	/**
	 * 保存角对于的菜单权限
	 * @param map {"roleId": 1, "permissions": ["菜单ID-权限ID", ....]}
	 * @return
	 */
	@PostMapping("/saveRolePermission")
    public Object saveRolePermission(@RequestBody RolePermissionVo dto) {
		
    	//先把该角色对于的权限全部删除
    	QueryWrapper<SystemRolePermission> queryWrapper = new QueryWrapper<SystemRolePermission>() ;
		queryWrapper.eq("role_id", dto.getRoleId()) ;
		this.rolePermissionService.remove(queryWrapper);
    	
    	if(null != dto.getPermissions()) {
    		for (String permission : dto.getPermissions()) {
    			String[] split = permission.split("-") ;
    			SystemRolePermission entity = new SystemRolePermission() ;
    			entity.setRoleId(dto.getRoleId());
    			entity.setMenuId(Long.parseLong(split[0]));
    			entity.setPermissionId(Long.parseLong(split[1]));
    			this.rolePermissionService.save(entity) ;
			}
    		return R.ok();
    	}
    	return R.failure("保存角色对应的菜单权限失败");
    }

}



